package cn.yll.api.util;

import cn.yll.common.constant.MyConstants;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * ip工具类
 * @author yangll
 */
public class IpUtil {
    /**
     * 获取用户真实IP地址，不使用request.getRemoteAddr();的原因是有可能用户使用了代理软件方式避免真实IP地址,
     * @param request servlet请求对象
     * @return 请求来源的真实ip地址
     */
    public static String getIpAddress(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (Objects.isNull(ip) || MyConstants.UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (Objects.isNull(ip) || MyConstants.UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (Objects.isNull(ip) || MyConstants.UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (Objects.isNull(ip) || MyConstants.UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (Objects.isNull(ip) || MyConstants.UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Real-IP");
        }
        if (Objects.isNull(ip) || MyConstants.UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }

        //对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
        if (ip != null && ip.length() > MyConstants.IP_MAX_LENGTH) {
            //"***.***.***.***".length() = 15
            if (ip.contains(MyConstants.IP_SPLIT)) {
                ip = ip.split(",")[0];
            }
        }
        return ip;
    }
}
